<template>
  <el-dialog class="dialog" :title="editOrAdd ? '产品选择' : '产品详情'" center="center" :visible.sync="dialogTableVisible">
    <el-form class="search_wrap" :model="filters" :inline="true">
      <el-form-item label="商户：">
        <el-select
          v-model="filters.businessId"
          clearable
          filterable
          placeholder="请选择商户"
          @change="
            () => {
              if (!filters.businessId) {
                departList = [];
              } else {
                getDepartList();
              }
            }
          "
        >
          <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门：">
        <el-cascader v-model="filters.departIds" :options="departList" clearable :props="{ value: 'departId', label: 'departName', checkStrictly: true }"> </el-cascader>
      </el-form-item>
      <el-form-item prop="businessClassifyIds" label="商户分类：">
        <el-select class="business-classify_select" v-model="filters.businessClassifyIds" clearable filterable multiple>
          <el-option v-for="item in businessClassifyList" :value="item.id" :label="item.name" :key="item.id">
            <div class="business-classify_name" v-html="item.name"></div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称：">
        <el-input v-model="filters.name" clearable placeholder="请输入产品名称"></el-input>
      </el-form-item>
      <el-form-item label="产品类型：">
        <el-select v-model="filters.goodsType" clearable filterable placeholder="请选择产品类型">
          <el-option :value="1" label="普通" />
          <el-option :value="2" label="套餐" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品编号：">
        <el-input type="number" v-model="filters.serverNo" clearable placeholder="请输入产品编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="getData()">查询</el-button>
        <el-button @click="getData(true)">全部</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="tableList" style="overflow: hidden" :data="tableData" max-height="600">
      <el-table-column prop="img" label="产品图片" width="200" align="center">
        <template slot-scope="scope">
          <div class="img-wrapper">
            <el-image v-if="scope.row.img" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" width="200" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品类型" width="200" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.idType == 1 ? '单品' : '套餐包' }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="introduce" label="产品简介" width="200" align="center"> </el-table-column>
      <el-table-column prop="salePrice" label="售价" align="center" width="180"></el-table-column>
      <el-table-column prop="businessName" label="商户名" width="150" align="center"> </el-table-column>
      <el-table-column prop="departName" label="部门" width="150" align="center"> </el-table-column>
      <el-table-column label="数量" width="150" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.num" v-maxnum="{ obj: scope.row, key: 'num', int: true }"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="是否首页显示" width="120" align="center" v-if="moduleType == 4">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.outShow" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="serverNo" label="产品自定义编号" align="center" :width="editOrAdd ? 170 : 130">
        <template slot-scope="scope">
          <div v-if="editOrAdd">
            <el-input clearable type="number" v-model="scope.row.serverNo" @input="handleServerNoInput(scope.row, scope.$index)"></el-input>
          </div>
          <div v-else>
            {{ scope.row.serverNo }}
          </div>
        </template>
        <template slot="header" slot-scope="scope">
          <div>
            产品自定义编号
            <el-button v-if="editOrAdd" @click="handleSelfAdd" type="success" style="padding: 4px 8px" size="mini">自增</el-button>
            <el-button v-if="editOrAdd" @click="handleDelNo" type="danger" style="padding: 4px 8px" size="mini">删除编号</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="默认选择" align="center" width="100">
        <template slot-scope="scope">
          <div v-if="editOrAdd">
            <el-button v-if="!scope.row.defaultFlag" plain type="info" size="mini" @click.native="handleDefaultClick(scope.row, scope.$index)">设为默认 </el-button>
            <el-button v-if="scope.row.defaultFlag" plain size="mini" type="success" @click.native="handleDefaultClick(scope.row, scope.$index)">默认 </el-button>
          </div>
          <div v-else>
            <el-button v-if="scope.row.defaultFlag" plain size="mini" type="success">默认</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 20px; text-align: center" v-if="editOrAdd">
      <el-button type="primary" @click="sureClick">保存</el-button>
      <el-button @click="cancelClick">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import GoodsApi from '@/api/goods/goods';
import BusinessServerApi from '@/api/goods/businessServer';
import BusinessDepartApi from '@/api/business/depart';
export default {
  props: {
    // 判断这个组件是用于新增编辑还是查看详情
    editOrAdd: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    editOrAdd: {
      handler(value) {
        // if (value) {
        //   this.title = "产品选择";
        // } else {
        //   this.title = "产品详情";
        // }
      },
      immediate: true,
    },
    // dialogTableVisible: {
    //   handler(value) {
    //     if (value) {
    //       this.tableData.sort((a, b) => {
    //         return Number(b.serverNo) - Number(a.serverNo);
    //       });
    //     }
    //   }
    // },
    async 'filters.businessId'() {
      this.filters.businessClassifyIds = [];
      this.departList = [];
      await this.getBusinessClassifyList();
      await this.getDepartList();
    },
    async 'filters.businessClassifyIds'(val) {
      if (val && val.length) this.getBusinessClassifyStyle();
    },
  },
  data() {
    return {
      filters: {
        businessId: '',
        businessClassifyIds: [],
        name: '',
        goodsType: '',
        serverNo: '',
        departIds: '',
      },
      // title: "",
      tableData: [],
      allList: [],
      index: undefined,
      dialogTableVisible: false,
      moduleType: '', //模块类型如果为5的话需要显示列是否在首页展示
      businessList: [],
      businessClassifyList: [],
      btnGoodsParams: [],
      departList: [],
    };
  },
  methods: {
    async showDialog({ params, moduleType, serverBtnParam, index, businessList, btnGoodsParams }) {
      Object.assign(this.$data, this.$options.data());
      Object.assign(this.filters, params);
      this.serverBtnParam = serverBtnParam;
      this.businessList = businessList;
      this.index = index;
      this.moduleType = moduleType;
      if (btnGoodsParams) this.btnGoodsParams = btnGoodsParams;
      await this.getData();
      this.dialogTableVisible = true;
    },
    // 获取数据
    async getData(all) {
      const { serverBtnParam, filters } = this;
      if (all) {
        filters.name = '';
        filters.goodsType = '';
        filters.serverNo = '';
        filters.businessId = '';
        filters.businessClassifyIds = [];
        filters.departIds = '';
      }
      const params = {
        ...filters,
        departId: filters.departIds[0] || '',
        firstDepartId: filters.departIds[1] || '',
        secondDepartId: filters.departIds[2] || '',
        thirdDepartId: filters.departIds[3] || '',
      };
      delete params.departIds;
      params.businessClassifyIds = params.businessClassifyIds.toString();
      params.businessId && (params.businessIds = params.businessId);
      Reflect.deleteProperty(params, 'businessId');
      const res = await GoodsApi.getMultipleGoods(params);
      if (serverBtnParam && serverBtnParam.length > 0 && !this.allList.length) {
        // 第一次赋值
        res.data.forEach((item) => {
          const target = serverBtnParam.find((item2) => item2.id == item.id && item2.idType == item.idType && item.businessId == item2.businessId);
          target && Object.keys(item).forEach((key) => (item[key] = target[key]));
        });
      }
      const _btnGoodsParams = [];
      res.data.forEach((item) => {
        if (item.idType === 1) {
          if (!this.btnGoodsParams.find((record) => record.serverId === item.serverId)) _btnGoodsParams.push(item);
        } else {
          if (!this.btnGoodsParams.find((record) => record.id === item.id)) _btnGoodsParams.push(item);
        }
      });

      let listData = [...this.btnGoodsParams, ..._btnGoodsParams];
      if (!this.allList.length) {
        this.allList = listData;
      } else {
        listData.forEach((item, index) => {
          const target = this.allList.find((item2) => item2.id == item.id && item2.idType == item.idType && item2.businessId == item.businessId);
          listData.splice(index, 1, target);
        });
      }
      if (filters.businessId || filters.name || filters.goodsType || filters.businessClassifyIds.length > 0) {
        const resIds = new Set(res.data.map((item) => item.id));
        listData = listData.filter((item) => resIds.has(item.id));
      }
      if (filters.serverNo) {
        listData = listData.filter((item) => item.serverNo === Number(filters.serverNo));
      }
      this.tableData = listData;
      this.tableData.sort((a, b) => {
        return Number(b.serverNo) - Number(a.serverNo);
      });
    },
    // 获取服务分类列表
    // async getServet
    async getBusinessClassifyList() {
      const { businessId } = this.filters;
      if (!businessId) return (this.businessClassifyList = []);
      const res = await BusinessServerApi.classifyListIdName({ businessId });
      this.businessClassifyList = res.data;
    },
    getBusinessClassifyStyle() {
      this.$nextTick(() => {
        const { businessClassifyList, filters } = this;
        const els = document.querySelectorAll('.business-classify_select .el-select__tags-text');
        filters.businessClassifyIds.forEach((item, index) => {
          const obj = businessClassifyList.find((item2) => item2.id == item);
          els[index].innerHTML = obj.name;
        });
      });
    },
    getDepartList() {
      let params = {
        businessId: this.filters.businessId,
      };
      BusinessDepartApi.listMangerTree(params).then((res) => {
        this.departList = res.data;
      });
    },
    sureClick() {
      const { allList } = this;
      if (!allList.some((item) => item.serverNo)) {
        this.$message.error('请至少选择填写一个编号');
        return;
      }

      if (!allList.some((item) => item.defaultFlag)) {
        this.$message.error('请选择默认产品');
        return;
      }

      // 编号重复判断
      const serverNoCount = {};
      const duplicateServerNos = [];
      allList.forEach((item) => {
        const { serverNo } = item;
        // 记录每个 serverNo 的出现次数
        if (serverNo) {
          if (serverNoCount[serverNo]) {
            serverNoCount[serverNo] += 1;
          } else {
            serverNoCount[serverNo] = 1;
          }
        }
      });
      for (const serverNo in serverNoCount) {
        if (serverNoCount[serverNo] && serverNoCount[serverNo] > 1) {
          duplicateServerNos.push(Number(serverNo));
        }
      }

      if (duplicateServerNos.length > 0) {
        this.$message.error(`编号 ${duplicateServerNos.toString()} 重复`);
        return;
      }
      this.$emit('saveServerData', { tableData: allList, index: this.index });
      this.cancelClick();
    },
    cancelClick() {
      this.dialogTableVisible = false;
    },

    // handleOutshow(row) {
    //   // if (this.tableData.filter(item => item.outShow == 1).length > 5) {
    //   //   this.$message.error("最多只能选择5个");
    //   //   row.outShow = 0;
    //   // }
    // },
    handleServerNoInput(row) {
      let reg = /\d$/;
      if (row.serverNo && !reg.test(row.serverNo)) {
        row.serverNo = '';
        this.$message.error('只能输入数字');
      }
      if (!row.serverNo && row.defaultFlag) {
        row.defaultFlag = 0;
      }
    },
    handleDefaultClick(row, rowindex) {
      let item = this.tableData.find((item, index) => index == rowindex);
      if (!item.defaultFlag && !item.serverNo) {
        this.$message.error('请先填写编号再设置默认');
        return;
      }
      this.allList.forEach((item) => {
        item.defaultFlag = 0;
      });
      item.defaultFlag = 1;
    },
    handleSelfAdd() {
      let no = 0;
      if (this.tableData.some((item) => item.serverNo)) {
        this.$confirm('已填写编号，自增后会覆盖原编号，是否继续？', '提示', {}).then((res) => {
          this.tableData.forEach((item) => {
            item.serverNo = ++no;
          });
        });
      } else {
        this.tableData.forEach((item) => {
          item.serverNo = ++no;
        });
      }
    },
    async handleDelNo() {
      await this.$confirm('确定删除所有编号', '提示', {});
      this.tableData.forEach((item) => (item.serverNo = ''));
    },
  },
};
</script>
<style scoped lang="scss">
.dialog {
  &::v-deep .el-dialog {
    width: 80%;
    margin-top: 5vh !important;
  }

  .img-wrapper {
    width: 80px;
    height: 60px;
    overflow: hidden;
    border-radius: 3px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin: 0 auto;

    .el-image {
      width: 100%;

      &::v-deep img {
        width: 100%;
        height: auto;
      }
    }
  }
}
</style>
